package com.laoli.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entity.CourseComment;
import com.entity.CourseCommentFavoriteRecord;
import com.laoli.mapper.CourseCommentDao;
import com.laoli.mapper.CourseCommentFavoriteRecordDao;
import com.laoli.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CourseCommentDao courseCommentDao;
    @Autowired
    private CourseCommentFavoriteRecordDao courseCommentFavoriteRecordDao;
    @Override
    public Integer saveComment(CourseComment comment) {
        return courseCommentDao.insert(comment);
    }
    @Override
    public List<CourseComment> getCommentsByCourseId(Integer courseid, Integer offset, Integer pageSize) {
        return courseCommentDao.getCommentsByCourseId(courseid,offset,pageSize);
    }
    
    //保存赞
    @Override
    public  Integer saveFavorite(Integer comment_id, Integer userid) {
        QueryWrapper<CourseCommentFavoriteRecord> q=new QueryWrapper();
        q.eq("comment_id",comment_id);
        q.eq("user_id",userid);
        Integer i= courseCommentFavoriteRecordDao.selectCount(q);
        int i1=0;
        int i2=0;
        CourseCommentFavoriteRecord  favoriteRecord=new CourseCommentFavoriteRecord();
        favoriteRecord.setIsDel(0);
        if (i==0){//没有点过赞
            //添加赞的信息
            favoriteRecord.setUserId(userid);
            favoriteRecord.setCreateTime(new Date());
            favoriteRecord.setUpdateTime(new Date());
            favoriteRecord.setCommentId(comment_id);
            i1=courseCommentFavoriteRecordDao.insert(favoriteRecord);
        }
        else {
            i1=courseCommentFavoriteRecordDao.update(favoriteRecord,q);
        }
        i2=courseCommentDao.updateLikeCount(1,comment_id);
        if(i1==0 ||i2==0){
            throw new RuntimeException("点赞失败");
        }
        return comment_id;
    }
    //取消赞
    @Override
    public  Integer cancelFavorite(Integer comment_id, Integer userid) {
        QueryWrapper<CourseCommentFavoriteRecord> q=new QueryWrapper();
        q.eq("comment_id",comment_id);
        q.eq("user_id",userid);
        CourseCommentFavoriteRecord  favoriteRecord=new CourseCommentFavoriteRecord();
        favoriteRecord.setIsDel(1);//表示该赞被取消
        Integer i1=courseCommentFavoriteRecordDao.update(favoriteRecord,q);
        Integer i2=courseCommentDao.updateLikeCount(-1,comment_id);
        if(i1==0 ||i2==0 ){
            throw new RuntimeException("取消点赞失败");
        }
        return i2;  
    }
}
